#include "server.h"
#include <iostream>
using namespace std;

Server::Server(QObject * parent, int port): QTcpServer(parent)
{
    //绑定IP和端口，开始监听
    listen(QHostAddress::Any, port);
    if(isListening())
        cout<<"is lestening.."<<endl;
}

//当有Client建立连接时，触发incommingConnectio()，
void Server::incomingConnection(int clientDiscriptor)
{
    cout<<"got one!"<<endl;
    Client * item = new Client(this);

    //绑定server的updateClients槽和client的updateCliens信号
    connect(item, SIGNAL(updateClients(QString, int)),
            this, SLOT(updateClients(QString, int)));
    //绑定client的disconnected的信号和server的slotDisconnected槽
    connect(item, SIGNAL(disconnected(int)),
            this, SLOT(slotDisconnected(int)));

    item->setSocketDescriptor(clientDiscriptor);
    clientList.append(item);
}

//Client的updateClients信号传递至该槽
void Server::updateClients(QString msg, int length)
{
    //调用Server的updateServer信号，由TcpServerUI的slotUpdateServer槽获取信号
    //向TcpServerUI传递msg，传至TcpServerUI，用以更新UI显示的信息
    emit updateServer(msg, length);

    //遍历clientList，向每个进入聊天室的Client传递信息
    for(int i = 0;i < clientList.count(); i++)
    {
        Client * item = clientList.at(i);
        //Client继承自QTcpSocket，QTcpSocket继承自QAbstractSocket,
        //QAbstarctSocket继承自QIODevice
        //write函数来自QIODevice，传递数据
        item->write(msg.toLatin1(), length);
    }
}

//Client的disconnected信号传递至该槽，并传递参数socketDiscriptor
void Server::slotDisconnected(int clientDiscriptor)
{
    //遍历clientList，通过clientDiscirptor，找出是哪一个
    //client断开连接，然后从clientList中remove
    for(int i = 0; i < clientList.count(); i++)
    {
        Client * item = clientList.at(i);
        if(item->socketDescriptor() == clientDiscriptor)
        {
            clientList.removeAt(i);
            return;
        }
    }
    return;
}



